package com.shengruan.user.action;

import java.util.Date;
import java.util.List;

import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.lang.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.shengruan.admin.jdbc.PayParameterJdbc;
import com.shengruan.admin.jdbc.UserRechargeJdbc;
import com.shengruan.admin.vo.PayParameter;
import com.shengruan.admin.vo.User;
import com.shengruan.admin.vo.UserRecharge;
import com.shengruan.common.BaseAction;
import com.shengruan.common.Constants;
import com.shengruan.common.Function;
import com.shengruan.common.alipay.AlipayBase;
import com.shengruan.common.alipay.AlipayService;
import com.shengruan.framework.pager.Pager;

public class UserRechargeAction extends BaseAction {

    Logger logger = LoggerFactory.getLogger(getClass());

 
    private UserRechargeJdbc userRechargeJdbc = (UserRechargeJdbc) this.getJdbc(UserRechargeJdbc.class);
    private PayParameterJdbc payParameterJdbc = (PayParameterJdbc) this.getJdbc(PayParameterJdbc.class);


    /**
     * 加载充值界面
     *
     * @throws Exception
     */
    public void load() throws Exception {
        List<PayParameter> payParameterList = this.payParameterJdbc.findAll();
        this.setRequest("payParameterList", payParameterList);
        this.forward("/user/user-recharge.jsp");
        
    }

    /**
     * 用户充值
     *
     * @throws Exception
     */
    public void recharge() throws Exception {
        String bidding = this.input("bidding");
        String giftBidding = this.input("giftBidding");
        String amount = this.input("amount");


        this.setRequest("bidding", bidding);
        this.setRequest("giftBidding", giftBidding);
        this.setRequest("amount", amount);

        this.saveToken();
        this.forward("/user/user-recharge-details.jsp");
    }

    public void alipayment() throws Exception {
        //表单重复提交
        if (this.isTokenValid()) {
            List<PayParameter> payParameterList = this.payParameterJdbc.findAll();
            this.setRequest("payParameterList", payParameterList);
            this.forward("/user/user-recharge.jsp");
            return;
        }

        String bidding = this.input("bidding");
        String giftBidding = this.input("giftBidding");
        String amount = this.input("amount");
        String aliorder = this.input("aliorder");
        String alibody = this.input("alibody");
        String pay_bank = this.input("pay_bank");

        User sessionUser = (User) this.request.getSession().getAttribute(Constants.USER);

        PropertiesConfiguration config = new PropertiesConfiguration("AlipayConfig.properties");
		String input_charset = config.getString("CharSet");
		String sign_type = config.getString("sign_type");
		String seller_email = config.getString("sellerEmail");
		String partner = config.getString("partnerID");
		String key = config.getString("key");


		String show_url = config.getString("show_url");
		String notify_url = config.getString("notify_url");
		String return_url = config.getString("return_url");

		String antiphishing = config.getString("antiphishing");

		///////////////////////////////////////////////////////////////////////////////////


        //以下参数是需要通过下单时的订单数据传入进来获得
		//必填参数
        String out_trade_no = DateFormatUtils.format(new Date(), "yyyyMMddHHmmss");//调取支付宝工具类生成订单号,请与贵网站订单系统中的唯一订单号匹配
        //订单名称，显示在支付宝收银台里的“商品名称”里，显示在支付宝的交易管理的“商品名称”的列表里。
        String subject = aliorder;
        //订单描述、订单详细、订单备注，显示在支付宝收银台里的“商品描述”里
        String body = alibody;
        //订单总金额，显示在支付宝收银台里的“应付总额”里
        String total_fee = amount;

        //扩展功能参数——网银提前
        String pay_mode = pay_bank;
        String paymethod = "";		//默认支付方式，四个值可选：bankPay(网银); cartoon(卡通); directPay(余额); CASH(网点支付)
        String defaultbank = "";	//默认网银代号，代号列表见http://club.alipay.com/read.php?tid=8681379
        if(pay_mode.equals("directPay")){
        	paymethod = "directPay";
        }
        else{
        	paymethod = "bankPay";
        	defaultbank = pay_mode;
        }

        //扩展功能参数——防钓鱼
        String encrypt_key  = new Date().getTime() + "";					//防钓鱼时间戳，初始值
        String exter_invoke_ip= Function.getIpAddr(request);					//客户端的IP地址，初始值
        if(antiphishing.equals("1")){
        	encrypt_key = AlipayBase.query_timestamp(partner);
        	exter_invoke_ip = Function.getIpAddr(request);;					//获取客户端的IP地址，建议：编写获取客户端IP地址的程序
        }

        //扩展功能参数——其他
        String extra_common_param = "";				//自定义参数，可存放任何内容（除=、&等特殊字符外），不会显示在页面上
        String buyer_email = sessionUser.getMobile();					//默认买家支付宝账号

         //扩展功能参数——分润(若要使用，请按照注释要求的格式赋值)
        String royalty_type = "";					//提成类型，该值为固定值：10，不需要修改
        String royalty_parameters ="";
		//提成信息集，与需要结合商户网站自身情况动态获取每笔交易的各分润收款账号、各分润金额、各分润说明。最多只能设置10条
		//提成信息集格式为：收款方Email_1^金额1^备注1|收款方Email_2^金额2^备注2
		//如：
		//royalty_type = "10"
		//royalty_parameters	= "111@126.com^0.01^分润备注一|222@126.com^0.01^分润备注二"

		//扩展功能参数——自定义超时(若要使用，请按照注释要求的格式赋值)
		//该功能默认不开通，需联系客户经理咨询
		//超时时间，不填默认是15天。八个值可选：1h(1小时),2h(2小时),3h(3小时),1d(1天),3d(3天),7d(7天),15d(15天),1c(当天)
		String it_b_pay = "";

        /////////////////////////////////////////////////////////////////////////////////////////////////////


        //POST方式传递，得到加密结果字符串。想POST方式传递，请把下面四行代码取消注释。
        String sHtmlText = AlipayService.BuildPostform(partner,seller_email,return_url,notify_url,show_url,out_trade_no,
		subject,body,total_fee,paymethod,defaultbank,encrypt_key,exter_invoke_ip,extra_common_param,buyer_email,
		royalty_type,royalty_parameters,it_b_pay,input_charset,key,sign_type);

        UserRecharge userRecharge = new UserRecharge();
        userRecharge.setUserId(sessionUser.getId());
        userRecharge.setBidding(Integer.valueOf(bidding));
        userRecharge.setGiftBidding(Integer.valueOf(giftBidding));
        userRecharge.setAmount(Double.valueOf(amount));
        userRecharge.setIp(Function.getIpAddr(this.request));
        userRecharge.setCreationTime(System.currentTimeMillis());
        userRecharge.setStatus(Constants.USER_RECHARGE_STATUS_PENDING);

        userRecharge.setOrderNo(out_trade_no);
        userRecharge.setOrderSubject(subject);
        userRecharge.setOrderBody(body);
        userRecharge.setBuyerEmail(buyer_email);
        userRechargeJdbc.save(userRecharge);

        this.setRequest("sHtmlText", sHtmlText);
        this.forward("/user/user-recharge-details-alipayto.jsp");
    }


    public void list() throws Exception {

    	User user = this.getCurrentUser();
        int currentPage = 1;
        try {
            currentPage = Integer.parseInt(this.input("currentPage"));
        } catch (Exception ex) {
        }

        Pager pager = new Pager(currentPage, userRechargeJdbc.getRows(user.getId()), 30);
        List<UserRecharge> userRechargeList = userRechargeJdbc.findWithPage(currentPage, 30,user.getId());


        this.setRequest("pager", pager);
        this.setRequest("userRechargeList", userRechargeList);
        this.forward("/user/user-recharge-list.jsp");
    }
}
